<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\BaseController;
use app\middleware\admin\Auth;
use app\model\Purchase as PurchaseModel;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Db;


class Purchase extends BaseController
{
    protected $middleware=[Auth::class];
    /**
     * 采购
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        $data=PurchaseModel::with(['admin','product'])->order('id','desc')->paginate(10);
        $product=\app\model\Product::select();
        return $this->success(compact('data','product'));
    }


    public function create()
    {
        $data=request()->param();
        $data['admin_id']=request()->userid;
        PurchaseModel::create($data);
        return $this->success();
    }


    public function update($id)
    {
        $data=request()->param();
        $data['admin_id']=request()->userid;
        return $this->success(PurchaseModel::where('id',$id)->update($data));
    }


    public function delete($id)
    {
        PurchaseModel::where('id',$id)->delete();
        return $this->success();
    }

    public function mail()
    {
        $params=request()->param();

        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->CharSet = "utf-8";                     //utf-8;
        $mail->Encoding = "base64";
        $mail->Host = env('MAIL.MAIL_HOST');
        $mail->SMTPAuth = true;
        $mail->Username = env('MAIL.MAIL_USERNAME');
        $mail->Password = env('MAIL.MAIL_PASSWORD');
        $mail->SMTPSecure = env('MAIL.MAIL_ENCRYPTION');
        $mail->Port = env('MAIL.MAIL_PORT');
        $mail->setFrom(env('MAIL.MAIL_FROM_ADDRESS'), env('MAIL.MAIL_FROM_NAME'));
        $mail->addAddress(trim($params['connection']));
        $mail->Subject = '採購通知';
        $mail->Body = '採購產品：'.$params['product']['name']
            .PHP_EOL.'採購數量：'.$params['num']
            .PHP_EOL.'採購金額：'.$params['money']
            .PHP_EOL.'採購備註：'.$params['desc'];
        $mail->send();
        PurchaseModel::where('id',$params['id'])->update(['status'=>1]);
        return $this->success();
    }

    /** 收貨
     * @param $id
     * @return \think\response\Json
     */
    public function signfor($id)
    {
        $data=request()->param();

        \app\model\Product::where('id',$data['product_id'])->inc('num',$data['num'])->update();
        PurchaseModel::where('id',$id)->update(['type'=>1]);
        Db::table('admin_log')->insert([
            'type'=>1,
            'admin_id'=>request()->userid,
            'content'=>$data['product']['name'].'库存增加'.$data['num'],
            'created_at'=>time()
        ]);
        return $this->success();
    }
}
